package top.codedance.iotp.converter.service.master.listenner;

import top.codedance.iotp.converter.ConverterApplication;
import top.codedance.iotp.converter.service.master.Master;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import org.apache.log4j.Logger;

public class SerialPortListener implements SerialPortDataListener {
    private static Logger logger = ConverterApplication.getLogger(SerialPortListener.class);
    private Master master;

    public SerialPortListener(Master master){
        this.master = master;
    }

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
    }

    public void serialEvent(SerialPortEvent serialPortEvent) {
        if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
            return;
        SerialPort serialPort = serialPortEvent.getSerialPort();
        int avai = serialPort.bytesAvailable();
        while (avai > 0) {
            final byte[] data = new byte[avai];
            serialPort.readBytes(data, avai);
            ConverterApplication.workerPool.submit(() -> {
                master.recover(data);
                logger.debug("Master readLength: " + data.length);
            });
            avai = serialPort.bytesAvailable();
        }
    }
}
